package com.pivotal.cloud.mybatis.processor;

import com.baomidou.mybatisplus.core.toolkit.AES;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;

/**
 * @className: com.pivotal.cloud.mybatis.processor.SecureEncryptProcessor
 * @projectName: PivotalCloud项目
 * @module: PivotalCloud项目-SecureEncryptProcessor类，主要位于Mybatis模块-安全加密处理器模块
 * @content: SecureEncryptProcessor-安全加密处理器
 * @author: Powered by Marklin
 * @datetime: 2025-11-06 02:05
 * @version: 1.0.0
 * @copyright: Copyright © 2018-2025 PivotalCloud Systems Incorporated. All rights
 * reserved.
 */
public class SecureEncryptProcessor implements EnvironmentPostProcessor {

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		String mpwKey = environment.getProperty("mpw.key");
		/**
		 * 处理加密内容
		 */
		if (StringUtils.isNotBlank(mpwKey)) {
			HashMap<String, Object> map = new HashMap<>();
			for (PropertySource<?> ps : environment.getPropertySources()) {
				if (ps instanceof OriginTrackedMapPropertySource) {
					OriginTrackedMapPropertySource source = (OriginTrackedMapPropertySource) ps;
					for (String name : source.getPropertyNames()) {
						Object value = source.getProperty(name);
						if (value instanceof String) {
							String str = (String) value;
							if (str.startsWith("mpw:")) {
								map.put(name, AES.decrypt(str.substring(4), mpwKey));
							}
						}
					}
				}
			}
			// 将解密的数据放入环境变量，并处于第一优先级上
			if (CollectionUtils.isNotEmpty(map)) {
				environment.getPropertySources().addFirst(new MapPropertySource("custom-encrypt", map));
			}
		}
	}

}
